# Maintainer: Dan Printzell <wild@archlinux.org>
# Contributor: Mihails Strasuns <public@dicebot.lv>
# Contributor: Sven-Hendrik Haase <sh@lutzhaase.com>

pkgname=('ldc' 'liblphobos')
groups=('dlang' 'dlang-ldc')
pkgver=1.35.0
_pkgcommit=9c1ae1efbbebcf21b73e7b710d508d0d5ca04454
_dversion=2.105.2
_clangversion=16 # related to where ldc2 looks for compiler-rt sanitizers
epoch=3
pkgrel=1
pkgdesc="A D Compiler based on the LLVM Compiler Infrastructure including D runtime and libphobos2"
arch=('loong64' 'x86_64')
url="https://github.com/ldc-developers/ldc"
license=('BSD')
makedepends=('git' 'cmake' 'llvm' 'ldc' 'ninja')
# Disable lto as linking the ldc2 binary fails
options=(!lto)

source=(
    "git+https://github.com/ldc-developers/ldc#commit=$_pkgcommit"
    "ldc-phobos::git+https://github.com/ldc-developers/phobos.git"
)

sha256sums=('SKIP'
            'SKIP')

prepare() {
    cd "$srcdir/ldc"

    git submodule init
    git config submodule.phobos.url "$srcdir/ldc-phobos"
    git -c protocol.file.allow=always submodule update

    # Set version used for path construction in getFullClangCompilerRTLibPath()
    sed -i "s/ldc::llvm_version_base/\"$_clangversion\"/" driver/linker-gcc.cpp
}

build() {
    cd "$srcdir/ldc"

    mkdir -p build && cd build

    cmake -GNinja \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_SKIP_RPATH=ON \
    -DINCLUDE_INSTALL_DIR=/usr/include/dlang/ldc \
    -DBUILD_SHARED_LIBS=BOTH \
    -DBUILD_LTO_LIBS=ON \
    -DLDC_WITH_LLD=OFF \
    -DD_COMPILER_FLAGS="-link-defaultlib-shared=false -linker=gold --flto=thin" \
    -DADDITIONAL_DEFAULT_LDC_SWITCHES="\"-link-defaultlib-shared\"," \
    ..
    ninja
}

check() {
    cd "$srcdir/ldc/build"
    ninja all-test-runners
}

package_ldc() {
    depends=('liblphobos' 'llvm-libs' 'gcc' 'compiler-rt')
    backup=('etc/ldc2.conf')
    provides=("d-compiler=$_dversion")

    cd "$srcdir/ldc/build"
    DESTDIR="$pkgdir" ninja install

    # move bash-completion
    mkdir -p "$pkgdir/usr/share/bash-completion/completions/"
    mv "$pkgdir/etc/bash_completion.d/ldc2" "$pkgdir/usr/share/bash-completion/completions/"
    rm -rf "$pkgdir/etc/bash_completion.d"

    # remove liblphobos files
    rm -rf "$pkgdir/usr/include"
    rm -rf "$pkgdir/usr/lib"

    # symlinks
    ln -s /usr/share/bash-completion/completions/ldc2 "$pkgdir/usr/share/bash-completion/completions/ldc"
    ln -s /usr/bin/ldc2 "$pkgdir/usr/bin/ldc"
    ln -s /usr/bin/ldmd2 "$pkgdir/usr/bin/ldmd"

    # licenses
    install -D -m644 "$srcdir/ldc/LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
}

package_liblphobos() {
    provides=('d-runtime' 'd-stdlib')
    depends=('curl')
    options=('staticlibs' '!strip')

    cd "$srcdir/ldc/build"
    DESTDIR="$pkgdir" ninja install

    # remove ldc files
    rm -rf "$pkgdir/usr/bin/"
    rm -rf "$pkgdir/etc/"

    # licenses
    install -D -m644 "$srcdir/ldc/LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
}
